from fullstack import app, api, db
from fullstack.utils import to_json
from fullstack.Models.member.Member import Member
from fullstack.Models.member.OauthMemberBind import OauthMemberBind
from flask_restful import Resource
from fullstack.utils import paginate
from flask import request, jsonify
from sqlalchemy import or_


# @app.route('/vue/member')
class MemberList(Resource):
    def get(self):
        # 查询参数
        resp = {'code': 200, 'data':[]}
        res = request.values
        query_info = res['query']
        pagenum = int(res['pagenum']) if (
            'pagenum' in res and res['pagenum']) else 1
        pagesize = int(res['pagesize']) if (
            'pagesize' in res and res['pagesize']) else 5
        ret = paginate(pagenum, pagesize)
        # 查询记录总数
        total = 0
        query = Member.query
        query=query.filter(or_(Member.nickname.like("%" + query_info + "%") if query_info is not None else "",
                         Member.mobile.like("%" + query_info + "%") if query_info is not None else ""))
        total=query.count()
        member_list=query.order_by(Member.id.desc()).offset(
            ret['offset']).limit(ret['limit']).all()
        member_array=[]
        if member_list:
            for item in member_list:
                temp_data={
                    'id':str(item.id),
                    'nickname':item.nickname,
                    'mobile':str(item.mobile),
                    'sex':item.sex,
                    'avatar':item.avatar,
                    'remain':str(item.remain),
                    'created_time':item.created_time.strftime('%Y-%m-%d %H:%M:%S')
                }
                member_array.append(temp_data)
        resp['data']=member_array
        resp['total']=total
        return jsonify(resp)

    def delete(self):
        print(request.values)
        res = request.values
        id = int(res['id'])
        sql = '''
        DELETE FROM members
        WHERE id={0}
        '''.format(id)
        result = db.engine.execute(sql)
        # r=dict((zip(result.keys(), result)))
        return jsonify(status=200)

    def patch(self):
        rest = request.json
        id = rest['data']['id']
        nickname = rest['data']['nickname']
        mobile = rest['data']['mobile']
        remain = rest['data']['remain']
        sql = '''
        UPDATE members
        SET nickname='{0}',mobile={1},remain={2}
        WHERE id={3}
        '''.format(nickname, mobile, remain, id)
        db.engine.execute(sql)
        return jsonify(status=200)


api.add_resource(MemberList, '/vue/api/members/list')
